package com.example.aiinterview.controller;

import com.example.aiinterview.model.Interview;
import com.example.aiinterview.model.InterviewQuestion;
import com.example.aiinterview.model.User;
import com.example.aiinterview.model.ChatMessage;
import com.example.aiinterview.service.InterviewService;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequiredArgsConstructor
public class InterviewController {

    private final InterviewService interviewService;
    private final UserService userService;

    @GetMapping("/interview")
    public String showInterviewPage(Model model, Authentication authentication) {
        User user = userService.findByUsername(authentication.getName());
        model.addAttribute("user", user);
        return "interview";
    }

    @PostMapping("/interview/start")
    public String startInterview(@RequestParam(value = "resumeFile", required = false) MultipartFile file,
                                 @RequestParam(value = "resumeText", required = false) String resumeText,
                                 @RequestParam("jobPosition") String jobPosition,
                                 Authentication authentication,
                                 RedirectAttributes redirectAttributes) {
        try {
            System.out.println(" 开始创建面试...");
            
            // Get resume content from either file or text input
            String resumeContent;
            if (file != null && !file.isEmpty()) {
                System.out.println(" 处理上传文件: " + file.getOriginalFilename());
                resumeContent = interviewService.extractTextFromFile(file);
            } else if (resumeText != null && !resumeText.trim().isEmpty()) {
                System.out.println(" 处理文本简历");
                resumeContent = resumeText;
            } else {
                System.out.println(" 未提供简历内容");
                redirectAttributes.addFlashAttribute("errorMessage", "Please provide a resume either by uploading a file or pasting text");
                return "redirect:/interview";
            }

            // Create new interview
            User user = userService.findByUsername(authentication.getName());
            System.out.println("👤 用户: " + user.getUsername());
            System.out.println("💼 职位: " + jobPosition);
            
            Interview interview = interviewService.createNewInterview(user, resumeContent, jobPosition);
            System.out.println("✅ 面试创建成功，ID: " + interview.getId());

            // 确保面试ID已生成
            if (interview.getId() == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "面试创建失败，请重试");
                return "redirect:/interview";
            }

            // 为聊天式面试生成第一个AI问题
            try {
                String firstQuestion = generateFirstQuestion(interview);
                if (firstQuestion != null && !firstQuestion.trim().isEmpty()) {
                    // 保存第一个AI问题到聊天记录
                    ChatMessage firstAIMessage = new ChatMessage();
                    firstAIMessage.setInterview(interview);
                    firstAIMessage.setSender(ChatMessage.MessageSender.AI);
                    firstAIMessage.setContent(firstQuestion);
                    firstAIMessage.setTimestamp(LocalDateTime.now());
                    interview.addChatMessage(firstAIMessage);
                    interviewService.saveInterview(interview);
                    System.out.println("Successfully generated and saved first question for interview " + interview.getId());
                } else {
                    System.out.println("Failed to generate first question for interview " + interview.getId() + ", using fallback");
                    // 使用备用问题
                    String fallbackQuestion = "请介绍一下您与" + (interview.getJobPosition() != null ? interview.getJobPosition() : "该职位") + "相关的经验";
                    ChatMessage firstAIMessage = new ChatMessage();
                    firstAIMessage.setInterview(interview);
                    firstAIMessage.setSender(ChatMessage.MessageSender.AI);
                    firstAIMessage.setContent(fallbackQuestion);
                    firstAIMessage.setTimestamp(LocalDateTime.now());
                    interview.addChatMessage(firstAIMessage);
                    interviewService.saveInterview(interview);
                }
            } catch (Exception e) {
                System.err.println("Error generating first question for interview " + interview.getId() + ": " + e.getMessage());
                e.printStackTrace();
                // 使用备用问题
                try {
                    String fallbackQuestion = "请介绍一下您与" + (interview.getJobPosition() != null ? interview.getJobPosition() : "该职位") + "相关的经验";
                    ChatMessage firstAIMessage = new ChatMessage();
                    firstAIMessage.setInterview(interview);
                    firstAIMessage.setSender(ChatMessage.MessageSender.AI);
                    firstAIMessage.setContent(fallbackQuestion);
                    firstAIMessage.setTimestamp(LocalDateTime.now());
                    interview.addChatMessage(firstAIMessage);
                    interviewService.saveInterview(interview);
                    System.out.println("Used fallback question for interview " + interview.getId());
                } catch (Exception ex) {
                    System.err.println("Failed to save fallback question: " + ex.getMessage());
                }
            }

            System.out.println("🔄 重定向到聊天面试页面: /chat-interview/" + interview.getId());
            return "redirect:/chat-interview/" + interview.getId();
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("errorMessage", "文件处理错误: " + e.getMessage());
            return "redirect:/interview";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "启动面试时出错: " + e.getMessage());
            return "redirect:/interview";
        }
    }


    @GetMapping("/interview/process/{interviewId}")
    public String processInterview(@PathVariable Long interviewId,
                                   @RequestParam int question,
                                   Authentication authentication,
                                   Model model) {
        User user = userService.findByUsername(authentication.getName());
        Interview interview = interviewService.findById(interviewId);

        // Check if interview belongs to current user
        if (!interview.getUser().getId().equals(user.getId())) {
            return "redirect:/interview";
        }

        // Get current question
        InterviewQuestion currentQuestion = null;
        for (InterviewQuestion q : interview.getQuestions()) {
            if (q.getQuestionNumber() == question) {
                currentQuestion = q;
                break;
            }
        }

        if (currentQuestion == null) {
            // All questions answered, evaluate and show results
            interviewService.evaluateAnswersAndFinalize(interview);
            return "redirect:/result/" + interviewId;
        }

        model.addAttribute("interview", interview);
        model.addAttribute("currentQuestion", currentQuestion);
        model.addAttribute("totalQuestions", interview.getQuestions().size());
        model.addAttribute("currentQuestionNumber", question);

        return "interview-process";
    }

    @PostMapping("/interview/answer/{interviewId}/{questionNumber}")
    public String submitAnswer(@PathVariable Long interviewId,
                               @PathVariable int questionNumber,
                               @RequestParam("answer") String answer,
                               Authentication authentication) {
        User user = userService.findByUsername(authentication.getName());
        Interview interview = interviewService.findById(interviewId);

        // Check if interview belongs to current user
        if (!interview.getUser().getId().equals(user.getId())) {
            return "redirect:/interview";
        }

        // Save the answer
        interviewService.saveUserAnswer(interview, questionNumber, answer);

        // Move to next question
        int nextQuestion = questionNumber + 1;
        return "redirect:/interview/process/" + interviewId + "?question=" + nextQuestion;
    }

    @GetMapping("/result/{interviewId}")
    public String showResult(@PathVariable Long interviewId,
                             Authentication authentication,
                             Model model) {
        User user = userService.findByUsername(authentication.getName());
        Interview interview = interviewService.findById(interviewId);

        // Check if interview belongs to current user
        if (!interview.getUser().getId().equals(user.getId())) {
            return "redirect:/interview";
        }

        model.addAttribute("interview", interview);
        model.addAttribute("questions", interview.getQuestions());

        return "result";
    }

    @GetMapping("/interviews")
    public String showUserInterviews(Authentication authentication, Model model) {
        User user = userService.findByUsername(authentication.getName());
        List<Interview> interviews = interviewService.findByUser(user);
        model.addAttribute("interviews", interviews);
        return "interview-history";
    }

    @GetMapping("/chat-interview/{interviewId}")
    public String showChatInterview(@PathVariable Long interviewId,
                                  Authentication authentication,
                                  Model model,
                                  RedirectAttributes redirectAttributes) {
        try {
            System.out.println("🔍 加载聊天面试页面，ID: " + interviewId);
            
            // 检查面试ID是否有效
            if (interviewId == null || interviewId <= 0) {
                System.out.println("❌ 无效的面试ID: " + interviewId);
                redirectAttributes.addFlashAttribute("errorMessage", "无效的面试ID");
                return "redirect:/interview";
            }
            
            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                System.out.println("❌ 用户未找到: " + authentication.getName());
                redirectAttributes.addFlashAttribute("errorMessage", "用户未找到，请重新登录");
                return "redirect:/login";
            }
            System.out.println("👤 用户验证成功: " + user.getUsername());
            
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                System.out.println("❌ 面试不存在，ID: " + interviewId);
                redirectAttributes.addFlashAttribute("errorMessage", "面试不存在，ID: " + interviewId);
                return "redirect:/interview";
            }
            System.out.println("✅ 面试找到: " + interview.getId() + ", 职位: " + interview.getJobPosition());

            // 检查面试是否属于当前用户
            if (interview.getUser() == null || !interview.getUser().getId().equals(user.getId())) {
                redirectAttributes.addFlashAttribute("errorMessage", "无权访问该面试");
                return "redirect:/interview";
            }

            // 确保面试有必要的属性
            if (interview.getCurrentQuestionNumber() == null) {
                interview.setCurrentQuestionNumber(1);
            }
            if (interview.getTotalQuestions() == null) {
                interview.setTotalQuestions(5);
            }

            model.addAttribute("interview", interview);
            model.addAttribute("currentQuestionNumber", interview.getCurrentQuestionNumber());
            model.addAttribute("totalQuestions", interview.getTotalQuestions());
            model.addAttribute("resumeSummary", interview.getResumeSummary());

            System.out.println(" 准备聊天面试页面");
            System.out.println(" 面试状态: " + interview.getStatus());
            System.out.println(" 当前问题: " + interview.getCurrentQuestionNumber() + "/" + interview.getTotalQuestions());
            System.out.println("聊天消息数量: " + (interview.getChatMessages() != null ? interview.getChatMessages().size() : 0));

            return "chat-interview";
        } catch (Exception ex) {
            // 记录详细错误信息
            System.err.println("Error loading chat interview " + interviewId + ": " + ex.getMessage());
            ex.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "加载面试页面失败：" + ex.getMessage());
            return "redirect:/interview";
        }
    }

    @GetMapping("/test")
    public String testPage() {
        return "test-chat";
    }
    
    @GetMapping("/debug-interview/{interviewId}")
    public String debugInterview(@PathVariable Long interviewId,
                                Authentication authentication,
                                Model model,
                                RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findByUsername(authentication.getName());
            Interview interview = interviewService.findById(interviewId);
            
            model.addAttribute("interview", interview);
            model.addAttribute("user", user);
            
            return "debug-interview";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "调试失败：" + e.getMessage());
            return "redirect:/interview";
        }
    }
    
    private String generateFirstQuestion(Interview interview) {
        try {
            StringBuilder context = new StringBuilder();
            context.append("你是一名专业的面试官，正在对候选人进行面试。\n\n");
            context.append("职位信息：").append(interview.getJobPosition() != null ? interview.getJobPosition() : "未指定").append("\n\n");
            context.append("候选人简历分析：\n").append(interview.getResumeSummary() != null ? interview.getResumeSummary() : "无简历信息").append("\n\n");
            context.append("面试要求：\n");
            context.append("1. 这是面试的第一个问题，需要能够快速了解候选人的基本情况\n");
            context.append("2. 问题应该与目标职位相关，能够评估候选人的专业技能和经验\n");
            context.append("3. 问题应该开放性强，让候选人有充分展示的机会\n");
            context.append("4. 问题应该专业且友好，营造良好的面试氛围\n\n");
            context.append("请根据以上信息，提出一个合适的第一个面试问题。\n");
            context.append("要求：问题简洁明了，直接给出问题内容，不要包含其他说明文字。");
            
            String question = interviewService.generateFirstQuestion(context.toString());
            System.out.println("Generated first question: " + question);
            
            // 清理问题内容，移除可能的编号或多余文字
            if (question != null && !question.trim().isEmpty()) {
                question = question.trim();
                // 移除开头的数字编号
                question = question.replaceFirst("^\\d+[.、]\\s*", "");
                // 移除"问题："等前缀
                question = question.replaceFirst("^问题[:：]\\s*", "");
            }
            
            return question;
        } catch (Exception e) {
            System.err.println("Error in generateFirstQuestion: " + e.getMessage());
            e.printStackTrace();
            String fallbackQuestion = "请简单介绍一下您自己，并说明您为什么对这个" + (interview.getJobPosition() != null ? interview.getJobPosition() : "职位") + "感兴趣？";
            System.out.println("Using fallback question: " + fallbackQuestion);
            return fallbackQuestion;
        }
    }
}
